package com.lzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.common.JwtUtil;
import com.lzy.common.QueryPageParam;
import com.lzy.dto.UserDto;
import com.lzy.entity.Result;
import com.lzy.entity.User;
import com.lzy.mapper.UserMapper;
import com.lzy.service.IMenuService;
import com.lzy.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.vo.LoginInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private IMenuService menuService;

    // 日志对象
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserServiceImpl.class);

    // 登录
    @Override
    public Result login(UserDto userDto) {
        // 校验参数
        if (userDto == null || userDto.getUserName() == null || userDto.getPassword() == null) {
            return Result.fail("用户名或密码不能为空");
        }

        // 查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userDto.getUserName());
        User user = this.getOne(wrapper);

        // 用户不存在
        if (user == null) {
            return Result.fail("用户不存在");
        }

        // 密码错误
        if (!user.getPassword().equals(userDto.getPassword())) {
            return Result.fail("密码错误");
        }

        // 生成token
        String token = jwtUtil.generateToken(user.getUserName());
        
        // 获取用户菜单权限
        List<?> menus = menuService.getMenusByRole(user.getRole());
        
        // 记录日志
        logger.info("用户[{}]登录成功，角色:{}, 获取菜单数量:{}", user.getUserName(), user.getRole(), menus != null ? menus.size() : 0);
        
        // 如果没有菜单权限，添加默认菜单
        if (menus == null || menus.isEmpty()) {
            logger.warn("用户[{}]没有菜单权限，将添加默认菜单", user.getUserName());
            // 可以在这里添加默认菜单处理逻辑
        }
        
        // 构建返回信息
        LoginInfoVO info = new LoginInfoVO();
        info.setId(user.getId());
        info.setUserName(user.getUserName());
        info.setRole(user.getRole());
        info.setToken(token);
        info.setMenus(menus);
        
        return Result.success(info);
    }

    // 注册
    @Override
    public Result register(@RequestBody UserDto userDto) {
        if (userDto == null || userDto.getUserName() == null || userDto.getPassword() == null) {
            return Result.fail("用户名或密码不能为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userDto.getUserName())
                .ne(User::getId, userDto.getId());
        if (this.getOne(wrapper) != null) {
            return Result.fail("用户名已存在");
        }

        logger.info("dto里面的数据"+userDto);
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setUserName(userDto.getUserName());
        user.setPassword(userDto.getPassword());
        user.setRole(userDto.getRole());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        int insert = userMapper.insert(user);
        logger.info("注册数据"+user);

        if (insert > 0){
            return Result.success("注册成功");
        }else {
            return Result.fail("注册失败");
        }
    }

    @Override
    public Result logout(Integer id) {
        boolean flag = userMapper.delUser(id);
        if (flag){
            return Result.success("注销成功");
        }else {
            return Result.fail("注销失败");
        }
    }

    // 新增用户
    @Override
    public Result createUser(@RequestBody UserDto userDto) {
        if (userDto == null || userDto.getUserName() == null || userDto.getPassword() == null) {
            return Result.fail("用户名或密码不能为空");
        }
        
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userDto.getUserName())
                .ne(User::getId, userDto.getId());
        if (this.getOne(wrapper) != null) {
            return Result.fail("用户名已存在");
        }
        
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return Result.success("用户创建成功");
        } else {
            return Result.fail("用户创建失败");
        }
    }
    
    // 更新用户
    @Override
    public Result updateUser(UserDto userDto) {
        if (userDto == null || userDto.getId() == null) {
            return Result.fail("用户ID不能为空");
        }
        
        User existingUser = userMapper.selectById(userDto.getId());
        if (existingUser == null) {
            return Result.fail("用户不存在");
        }
        
        // 保留创建时间
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(existingUser.getCreateTime());
        
        int update = userMapper.updateById(user);
        if (update > 0) {
            return Result.success("用户更新成功");
        } else {
            return Result.fail("用户更新失败");
        }
    }
    
    // 删除用户
    @Override
    public Result deleteUser(Integer id) {
        if (id == null || id <= 0) {
            return Result.fail("无效的用户ID");
        }
        
        int delete = userMapper.deleteById(id);
        if (delete > 0) {
            return Result.success("用户删除成功");
        } else {
            return Result.fail("用户删除失败");
        }
    }

    @Override
    public IPage<User> getPage(Page<User> page, HashMap<String, Object> param) {
        return userMapper.getPage(page, param);
    }

}
